package Thread;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskThreadSafetyExample {

    // 共享资源
    private static class SharedResource {
        private int counter = 0;

        public void increment() {
            counter++;
        }

        public int getCounter() {
            return counter;
        }
    }

    public static void main(String[] args) {
        // 创建共享资源
        SharedResource sharedResource = new SharedResource();

        // 创建 Timer 实例
        Timer timer = new Timer();

        // 创建多个 TimerTask 实例
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    sharedResource.increment();
                }
                System.out.println("任务1: Counter = " + sharedResource.getCounter());
            }
        };

        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    sharedResource.increment();
                }
                System.out.println("任务2: Counter = " + sharedResource.getCounter());
            }
        };

        // 安排任务
        timer.schedule(task1, 0);
        timer.schedule(task2, 1);

        // 为了保持主线程不退出，让其等待一段时间
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        timer.cancel();

        System.out.println("最终的数字： " + sharedResource.getCounter());
    }
}
